package com.gcosc.hly.codejava.service.impl;

import com.alibaba.fastjson.JSON;
import com.gcosc.hly.codejava.Utils.Base64Utils;
import com.gcosc.hly.codejava.Utils.MD5Utils;
import com.gcosc.hly.codejava.Utils.PathUtils;
import com.gcosc.hly.codejava.Utils.TokenUtils;
import com.gcosc.hly.codejava.entity.User;
import com.gcosc.hly.codejava.exception.BusinessException;
import com.gcosc.hly.codejava.result.Code;
import com.gcosc.hly.codejava.service.LoginService;
import com.gcosc.hly.codejava.service.UserService;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginServiceImpl implements LoginService {

    private final UserService userService;
    private final TokenUtils tokenUtils;

    private final MD5Utils md5Utils;
    private final PathUtils pathUtils;
    private final Base64Utils base64Utils;

    @Value("${login.gcosc}")
    private String gcoscIp;

    @Override
    public String login(User loginParams) {

        User user = null;

        if ("gcosc".equals(loginParams.getUserFrom())){
            user = loginGcosc(loginParams);
        }else {
            user = userService.lambdaQuery()
                    .eq(User::getAccount,loginParams.getAccount())
                    .eq(User::getPassword, loginParams.getPassword())
                    .one();
        }

        if (user == null){
            throw new BusinessException(Code.BUSINESS_ERR, "账号或密码错误");
        }

        String token = tokenUtils.getToken(user.getId(), user.getRoot());
        return token;
    }

    public User loginGcosc(User loginParams){
        User user = null;
        try {
            String text = Jsoup.connect(gcoscIp + "/api/user/getinfo?token=" + loginParams.getAccount()).ignoreContentType(true)
                    .post().text();
            int rspCode = (int) JSON.parseObject(text).get("rspCode");
            if (rspCode != 200){
                throw new BusinessException(Code.BUSINESS_ERR, JSON.parseObject(text).get("rspMsg").toString());
            }

            String data = JSON.parseObject(text).getString("data");
            user = User.builder()
                    .name(JSON.parseObject(data).getString("u_name"))
                    .account(JSON.parseObject(data).getString("u_stu"))
                    .root(JSON.parseObject(data).getString("uPermissions").equals("admin") ? 2 : 1)
                    .userFrom(loginParams.getUserFrom())
                    .build();

            User one = userService.lambdaQuery()
                    .eq(User::getAccount, user.getAccount())
                    .eq(User::getUserFrom, loginParams.getUserFrom())
                    .one();

            if (one == null){
                userService.save(user);
                return user;
            }

            user.setId(one.getId());
            userService.updateById(user);

        } catch (IOException e) {
            throw new BusinessException(Code.BUSINESS_ERR, "身份验证失败");
        }
        return user;
    }


//    @Override
//    public String loginMail(LoginParams loginParams) {
//        verificationMailService.isVerificationMail(loginParams.getMail(),loginParams.getSms());
//        User user = userService.getUserInfo(loginParams.getMail());
//        if (user == null){
//            throw new BusinessException(Code.BUSINESS_ERR, "邮箱错误");
//        }
//        String token = tokenUtils.getToken(user.getUserId(), user.getRoot());
//        return token;
//    }
//
//    @Override
//    public String register(RegisterParams params) {
//
//        // 检查验证码
//        verificationMailService.isVerificationMail(params.getMail(), params.getSms());
//
//        // 检查用户名称是否被占用
//        User one = userService.lambdaQuery()
//                .eq(User::getUserName, params.getUserName())
//                .one();
//        if (one != null){
//            Code.BUSINESS_ERR("用户名已被占用");
//        }
//
//        // 检查邮箱是否被占用
//        if (userService.lambdaQuery()
//                .eq(User::getMail, params.getMail())
//                .one() != null){
//            Code.BUSINESS_ERR("邮箱已被占用");
//        }
//
//        User user = new User();
//        user.setMail(params.getMail());
//        user.setRoot(UserRootEnum.USER.getValue());
//        user.setPassword(md5Utils.encrypt(params.getPassword()));
//        user.setUuid(UUID.randomUUID().toString());
//        user.setUserName(params.getUserName());
//        user.setUserImage(params.getUserImage());
//
//        // 创建用户文件夹
//        String replace = "\\" + params.getMail().replace("@", "");
//        FileUtils.file(pathUtils.path + pathUtils.imagesPath + replace);
//
//        if (StringUtils.isNotEmpty(params.getBase64())){
//            String s = base64Utils.GenerateImage(params.getBase64(),
//                    replace + UserEnum.HEAD_IMAGE.getValue());
//            user.setUserImage(s);
//        }
//
//        userService.save(user);
//        userLogService.addLog(user.getUserId(), 0, UserLogEnum.REGISTER, "");
//        return tokenUtils.getToken(user.getUserId(), user.getRoot());
//    }
}
